<?php
// api/departments.php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { exit(0); }

require_once 'db.php';

$method = $_SERVER['REQUEST_METHOD'];
$departmentID = $_GET['DepartmentID'] ?? null;

switch($method) {
    case "GET":
        try {
            if ($departmentID !== null) {
                $stmt = $pdo->prepare("SELECT * FROM Department WHERE DepartmentID = ?");
                $stmt->execute([$departmentID]);
                $dept = $stmt->fetch();
                if ($dept) {
                    echo json_encode($dept);
                } else {
                    http_response_code(404);
                    echo json_encode(["error" => "Department not found"]);
                }
            } else {
                $stmt = $pdo->query("SELECT * FROM Department ORDER BY DepartmentName ASC");
                $depts = $stmt->fetchAll();
                echo json_encode($depts);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(["error" => "Failed to retrieve departments", "details" => $e->getMessage()]);
        }
        break;

    case "POST":
        $data = json_decode(file_get_contents("php://input"), true);
        if (!isset($data['DepartmentName']) || empty(trim($data['DepartmentName']))) {
            http_response_code(400);
            echo json_encode(["error" => "DepartmentName is required"]);
            exit;
        }
        try {
             // Check duplicate name
            $stmtCheck = $pdo->prepare("SELECT DepartmentID FROM Department WHERE DepartmentName = ?");
            $stmtCheck->execute([$data['DepartmentName']]);
            if ($stmtCheck->fetch()) {
                http_response_code(409);
                echo json_encode(["error" => "Department name already exists"]);
                exit;
            }

            $stmt = $pdo->prepare("INSERT INTO Department (DepartmentName) VALUES (?)");
            $stmt->execute([trim($data['DepartmentName'])]);
            http_response_code(201);
            echo json_encode(["success" => true, "DepartmentID" => $pdo->lastInsertId()]);
        } catch (PDOException $e) {
             http_response_code(500);
             if ($e->getCode() == '23000') {
                  http_response_code(409);
                  echo json_encode(["error" => "Database constraint violation (e.g., name already exists)", "details" => $e->getMessage()]);
             } else {
                  echo json_encode(["error" => "Failed to add department", "details" => $e->getMessage()]);
             }
        }
        break;

    case "PUT":
        if ($departmentID === null) {
            http_response_code(400);
            echo json_encode(["error" => "DepartmentID is required for update"]);
            exit;
        }
        $data = json_decode(file_get_contents("php://input"), true);
        if (!isset($data['DepartmentName']) || empty(trim($data['DepartmentName']))) {
            http_response_code(400);
            echo json_encode(["error" => "DepartmentName is required"]);
            exit;
        }
        try {
             // Check duplicate name (excluding self)
            $stmtCheck = $pdo->prepare("SELECT DepartmentID FROM Department WHERE DepartmentName = ? AND DepartmentID != ?");
            $stmtCheck->execute([$data['DepartmentName'], $departmentID]);
            if ($stmtCheck->fetch()) {
                http_response_code(409);
                echo json_encode(["error" => "Department name already exists"]);
                exit;
            }

            $stmt = $pdo->prepare("UPDATE Department SET DepartmentName = ? WHERE DepartmentID = ?");
            $success = $stmt->execute([trim($data['DepartmentName']), $departmentID]);
             if ($success && $stmt->rowCount() > 0) {
                 echo json_encode(["success" => true, "message" => "Department updated"]);
            } elseif($success) {
                 http_response_code(404); // Or 200 OK with msg
                 echo json_encode(["error" => "Department not found or no changes made"]);
            } else {
                 http_response_code(500);
                 echo json_encode(["error" => "Failed to update department"]);
            }
        } catch (PDOException $e) {
             http_response_code(500);
              if ($e->getCode() == '23000') {
                  http_response_code(409);
                  echo json_encode(["error" => "Database constraint violation (e.g., name already exists)", "details" => $e->getMessage()]);
             } else {
                  echo json_encode(["error" => "Failed to update department", "details" => $e->getMessage()]);
             }
        }
        break;

    case "DELETE":
        if ($departmentID === null) {
            http_response_code(400);
            echo json_encode(["error" => "DepartmentID is required for deletion"]);
            exit;
        }
        try {
            // Attempt to delete. Foreign key constraints might prevent this.
            $stmt = $pdo->prepare("DELETE FROM Department WHERE DepartmentID = ?");
            $success = $stmt->execute([$departmentID]);
             if ($success && $stmt->rowCount() > 0) {
                echo json_encode(["success" => true, "message" => "Department deleted"]);
            } else {
                http_response_code(404);
                echo json_encode(["error" => "Department not found"]);
            }
        } catch (PDOException $e) {
            if ($e->getCode() == '23000') { // Foreign key constraint violation
                http_response_code(409); // Conflict
                echo json_encode(["error" => "Cannot delete department: It is referenced by students, teachers, or courses.", "details" => $e->getMessage()]);
            } else {
                http_response_code(500);
                echo json_encode(["error" => "Failed to delete department", "details" => $e->getMessage()]);
            }
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(["error" => "Method not allowed"]);
        break;
}
?>